package com.example.mydemo.utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.Cursor;
import android.util.Log;

public class DatabaseTools {
    public static boolean DEBUG = false;
    private DBOpenHelper mDbHelper;
    private SQLiteDatabase mDb = null;
    
    public static final int Result_fail = 2;
    public static final int Result_pass = 1;
    public static final int Result_NA = 0;
    
    public static final String Db_ItTableName = "ITEM_TEST_RESULT_TABLE";
    //public static final String Db_FtTableName = "FULL_TEST_RESULT_TABLE";
    //public static final String Db_PtTableName = "PCBA_TEST_RESULT_TABLE";
    public static final String Db_Title = "ITEM_TITLE";
    public static final String Db_Result = "TEST_RESULT";
    
    private static final int STATUS_ITEM_TEST = 0;
    private static final int STATUS_FULL_TEST = 1;
    private static final int STATUS_PCBA_TEST = 2;
    
    public static final int MAIN_FLASHLIGHT = 0;
    public static final int SUB_FLASHLIGHT = 1;
    public static String[] testItemName = new String[]{"test_main_camera","test_sub_camera","test_flashlight","test_wifi","test_bluetooth","test_gps","test_speaker",
          "test_gsensor","test_fm","test_battery","test_tp","test_lcd","test_dial","test_vibrate","test_record","test_sd","test_sim",
          "test_otg","button_key","test_emmc","test_memory_ddr","test_distance_calibration","test_gyroscope","test_msensor","test_nfc","test_hdmi","test_dc","test_hall","test_docking"
          ,"test_fingerprint","test_calibration","test_run_old","test_headset","test_audio","test_led","test_ScanningHead","test_psensor","test_receiver"};
    Context mContext=null;
    
    public DatabaseTools(Context context){
        mDbHelper = new DBOpenHelper(context);
        mDb = mDbHelper.getWritableDatabase();
    }
    
    public static int getItemPosition(String itemName){
        for(int i = 0;i < testItemName.length;i++){
            if(itemName.equals(testItemName[i]))return i;
        }
        return 0;
    }
    
    public boolean updateResult(String tableName,int item, int result){
        tableName = Db_ItTableName;
        ContentValues values = new ContentValues();
        String[] whereArgs = null;
        String where = Db_Title+"=?";
        values.put(Db_Result, result);
        
        if(mDb == null)return false;
            
        whereArgs = new String[]{testItemName[item]};
              
        String sortOrder = "_id DESC";
        Cursor c = null;
        if(mDb != null && isDbDataExist(tableName)){
            c =mDb.query(tableName, null, where, whereArgs, null, null, sortOrder);
        }
        if (c != null && c.getCount() > 0){
            if(DEBUG){
                Log.d("DatabaseTools"," c.getCount() " + c.getCount());
                while(c.moveToNext()){
                    String str = c.getString(c.getColumnIndexOrThrow(DatabaseTools.Db_Title));
                    Log.d("DatabaseTools"," str: " + str);
                }
                mDb.update(tableName, values, where, whereArgs);
            }
            c.close();
        }else{
           values.put(Db_Title, testItemName[item]);
           if(DEBUG)  Log.d("DatabaseTools","tableName:"+tableName+" insert  values:"+values);
           mDb.insert(tableName, null,values);
        } 
        return true;
    }

    public boolean updateResult(String tableName,String itemName, int result){
        tableName = Db_ItTableName;
        ContentValues values = new ContentValues();
        String[] whereArgs = null;
        String where = Db_Title+"=?";
        values.put(Db_Result, result);
        
        if(mDb == null)return false;
        whereArgs = new String[]{itemName};
    
        String sortOrder = "_id DESC";
        Cursor cursor = null;
        String sql = "select *  from " + tableName+" where "+Db_Title+" = \'"+itemName+"\' ";

        if(DEBUG)  Log.d("DatabaseTools"," updateResult sql: " + sql);
        if(mDb != null && isDbDataExist(tableName)){
            cursor =mDb.rawQuery(sql, null);
        }
        if (cursor != null && cursor.getCount() > 0){
            if(DEBUG){
                Log.d("DatabaseTools"," c.getCount() " + cursor.getCount());
                //cursor.moveToFirst();
                while(cursor.moveToNext()){
                    String str = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseTools.Db_Title));
                    int curResult = cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseTools.Db_Result));
                    Log.d("DatabaseTools"," str: " + str+" ,curResult:"+curResult);
                }
                Log.d("DatabaseTools","tableName:"+tableName+" update  values:"+values);
            }
            cursor.close();
            mDb.update(tableName, values, where, whereArgs);
        }else{
           values.put(Db_Title, itemName);
           if(DEBUG)  Log.d("DatabaseTools","tableName:"+tableName+" insert  values:"+values);
           mDb.insert(tableName, null,values);
        }     
        if(DEBUG)  Log.d("DatabaseTools"," updateResult result:" + result);
        return true;
    }

    public boolean isFulltestPass(){
        Cursor c = queryTableByName(Db_ItTableName);
        if (c != null && c.getCount() > 0){
            for(int i = 0;i < c.getCount();i++){
                c.moveToPosition(i);
                int status = c.getInt(c.getColumnIndexOrThrow(Db_Result));
                if(status == Result_fail || status == Result_NA)return false;
            }
        }
        return true;
    }
    
    public void setAutoTestResult(boolean isTestPass, int testStatus, String itemName){
        if(isTestPass){
            if(testStatus == STATUS_ITEM_TEST)
                updateResult(Db_ItTableName, getItemPosition(itemName), Result_pass);
            if(testStatus == STATUS_FULL_TEST)
                updateResult(Db_ItTableName, getItemPosition(itemName), Result_pass);
            if(testStatus == STATUS_PCBA_TEST)
                updateResult(Db_ItTableName, getItemPosition(itemName), Result_pass);
        }else{
            if(testStatus == STATUS_ITEM_TEST)
                updateResult(Db_ItTableName, getItemPosition(itemName), Result_fail);
            if(testStatus == STATUS_FULL_TEST)
                updateResult(Db_ItTableName, getItemPosition(itemName), Result_fail);
            if(testStatus == STATUS_PCBA_TEST)
                updateResult(Db_ItTableName, getItemPosition(itemName), Result_fail);
        }
    }

    public boolean isPCBAtestPass(){
        Cursor c = queryTableByName(Db_ItTableName);
        if (c != null && c.getCount() > 0){
            for(int i = 0;i < c.getCount();i++){
                c.moveToPosition(i);
                int status = c.getInt(c.getColumnIndexOrThrow(Db_Result));
                if(status != Result_pass)return false;
            }
        }
        return true;
    }
    
    public Cursor queryTableByName(String table){
        String[] projection = null; 
        String selection = "";
        String[] selectionArgs = null;
        String sortOrder = "_id DESC";
        Cursor cursor = null;
        if(mDb != null && isDbDataExist(table))
            cursor =mDb.query(table, projection, selection, selectionArgs, null, null, sortOrder);
        return cursor;
    }
    
    public boolean isDbDataExist(String tableName){
        boolean result = false;
        String sql = "select count(*) count from " + tableName;
        if(mDb != null){
            Cursor cursor = mDb.rawQuery(sql, null);
            if (cursor.moveToNext() ) {
                int count = cursor.getInt(0);
                if(count>0){
                    result = true;
                }
                cursor.close();
                //mDb.close();
            }
        }
        //android.util.Log.d("DatabaseTools","isDbDataExist tableName: "+result);
        return result;
    }

    public boolean clearDbData(String tableName){
        boolean result = false;
        String sql = "DELETE FROM "+tableName;
        if(DEBUG) Log.d("DatabaseTools"," clearDbData sql: " + sql);
        if(mDb != null && isDbDataExist(tableName)){
            mDb.execSQL(sql);
            result = true;
        }
        //android.util.Log.d("DatabaseTools","isDbDataExist tableName: "+result);
        return result;
    }
}
